package info.amber.vboot.jms;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.scheduling.annotation.EnableAsync;

import javax.jms.Queue;
import javax.jms.Topic;

@Configuration
@EnableJms
@EnableAsync
public class ActiveMQConfig {

    public static final String QUEUE_DEMO = "queue.demo";
    public static final String TOPIC_DEMO = "topic.demo";

    @Value("${spring.activemq.user:admin}")
    private String userName;

    @Value("${spring.activemq.password:admin}")
    private String password;

    @Value("${spring.activemq.broker-url}")
    private String brokerUrl;

    @Bean
    public Queue queue() {
        return new ActiveMQQueue(QUEUE_DEMO);
    }

    @Bean
    public Topic topic() {
        return new ActiveMQTopic(TOPIC_DEMO);
    }

    @Bean
    public ActiveMQConnectionFactory connectionFactory() {
        return new ActiveMQConnectionFactory(userName, password, brokerUrl);
    }

    @Bean
    public JmsListenerContainerFactory<?> jmsListenerContainerQueue(ActiveMQConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        bean.setConnectionFactory(connectionFactory);
        return bean;
    }

    @Bean
    public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ActiveMQConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        // 设置为发布订阅方式, 默认情况下使用的生产消费者方式
        bean.setPubSubDomain(true);

        bean.setConnectionFactory(connectionFactory);
        return bean;
    }
}
